<template>
  <div class="query-tool">
    <div class="page-header">
      <h1>SQL查询工具</h1>
      <div class="header-actions">
        <el-select v-model="selectedConnection" placeholder="选择数据库连接" style="width: 200px; margin-right: 10px;">
          <el-option
            v-for="conn in connectionList"
            :key="conn.id"
            :label="conn.name"
            :value="conn.id"
          />
        </el-select>
        <el-button type="primary" @click="executeQuery" :disabled="!selectedConnection || !queryText.trim()">
          <el-icon><CaretRight /></el-icon>
          执行查询
        </el-button>
      </div>
    </div>

    <div class="query-container">
      <el-row :gutter="20">
        <!-- 查询编辑器 -->
        <el-col :span="24">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>SQL查询编辑器</span>
                <div class="editor-actions">
                  <el-button size="small" @click="clearQuery">清空</el-button>
                  <el-button size="small" @click="formatQuery">格式化</el-button>
                  <el-button size="small" @click="showHistory">历史记录</el-button>
                </div>
              </div>
            </template>
            
            <div class="query-editor">
              <el-input
                v-model="queryText"
                type="textarea"
                :rows="10"
                placeholder="请输入SQL查询语句..."
                class="query-textarea"
              />
            </div>
            
            <div class="query-info" v-if="lastExecution">
              <span>执行时间: {{ lastExecution.execution_time }}ms</span>
              <span v-if="lastExecution.rows_affected">影响行数: {{ lastExecution.rows_affected }}</span>
              <span v-if="lastExecution.row_count">返回行数: {{ lastExecution.row_count }}</span>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 查询结果 -->
      <el-row :gutter="20" style="margin-top: 20px;" v-if="queryResult">
        <el-col :span="24">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>查询结果</span>
                <div class="result-actions">
                  <el-button size="small" @click="exportResult" v-if="queryResult.columns">
                    <el-icon><Download /></el-icon>
                    导出
                  </el-button>
                </div>
              </div>
            </template>
            
            <!-- 成功结果 -->
            <div v-if="queryResult.success">
              <!-- SELECT查询结果 -->
              <div v-if="queryResult.columns">
                <el-table :data="queryResult.rows" style="width: 100%" max-height="400">
                  <el-table-column
                    v-for="(column, index) in queryResult.columns"
                    :key="index"
                    :prop="index.toString()"
                    :label="column"
                    show-overflow-tooltip
                  />
                </el-table>
                <div class="result-summary">
                  共 {{ queryResult.row_count }} 行数据
                </div>
              </div>
              
              <!-- 非SELECT查询结果 -->
              <div v-else class="execution-result">
                <el-result icon="success" title="执行成功">
                  <template #sub-title>
                    <p v-if="queryResult.rows_affected !== undefined">
                      影响了 {{ queryResult.rows_affected }} 行数据
                    </p>
                  </template>
                </el-result>
              </div>
            </div>
            
            <!-- 错误结果 -->
            <div v-else class="error-result">
              <el-result icon="error" title="执行失败">
                <template #sub-title>
                  <p>{{ queryResult.message }}</p>
                </template>
              </el-result>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 查询历史对话框 -->
    <el-dialog v-model="historyDialogVisible" title="查询历史" width="80%">
      <el-table :data="queryHistory" style="width: 100%" max-height="500">
        <el-table-column prop="connection_name" label="数据库" width="150" />
        <el-table-column prop="query_type" label="类型" width="100" />
        <el-table-column prop="query" label="查询语句" show-overflow-tooltip />
        <el-table-column prop="execution_time" label="执行时间" width="100">
          <template #default="scope">
            {{ scope.row.execution_time }}ms
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
              {{ scope.row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="executed_at" label="执行时间" width="180" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="text" size="small" @click="useHistoryQuery(scope.row)">
              使用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="historyPagination.page"
          v-model:page-size="historyPagination.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="historyPagination.total"
          layout="total, sizes, prev, pager, next"
          @size-change="fetchQueryHistory"
          @current-change="fetchQueryHistory"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { CaretRight, Download } from '@element-plus/icons-vue'
import api from '@/utils/api'

// 响应式数据
const selectedConnection = ref(null)
const queryText = ref('')
const queryResult = ref(null)
const lastExecution = ref(null)
const historyDialogVisible = ref(false)

const connectionList = ref([])
const queryHistory = ref([])

const historyPagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 方法
const fetchConnectionList = async () => {
  try {
    const response = await api.get('/database/connections/')
    if (response.data.success) {
      let data = response.data.data
      
      if (Array.isArray(data)) {
        connectionList.value = data.filter((conn: any) => conn.is_active)
      } else if (data && Array.isArray(data.results)) {
        connectionList.value = data.results.filter((conn: any) => conn.is_active)
      }
    }
  } catch (error) {
    console.error('获取连接列表失败:', error)
  }
}

const executeQuery = async () => {
  if (!selectedConnection.value || !queryText.value.trim()) {
    ElMessage.warning('请选择数据库连接并输入查询语句')
    return
  }

  try {
    const response = await api.post('/database/execute-query/', {
      connection_id: selectedConnection.value,
      query: queryText.value.trim()
    })

    if (response.data.success) {
      queryResult.value = {
        success: true,
        ...response.data.data
      }
      lastExecution.value = {
        execution_time: response.data.execution_time,
        rows_affected: response.data.data.rows_affected,
        row_count: response.data.data.row_count
      }
      ElMessage.success('查询执行成功')
    } else {
      queryResult.value = {
        success: false,
        message: response.data.message
      }
      lastExecution.value = {
        execution_time: response.data.execution_time || 0
      }
    }
  } catch (error: any) {
    console.error('查询执行失败:', error)
    queryResult.value = {
      success: false,
      message: error.response?.data?.message || '查询执行失败'
    }
    ElMessage.error('查询执行失败')
  }
}

const clearQuery = () => {
  queryText.value = ''
  queryResult.value = null
  lastExecution.value = null
}

const formatQuery = () => {
  // 简单的SQL格式化
  let formatted = queryText.value
    .replace(/\s+/g, ' ')
    .replace(/\s*,\s*/g, ',\n  ')
    .replace(/\s*(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT)\s+/gi, '\n$1 ')
    .replace(/\s*(AND|OR)\s+/gi, '\n  $1 ')
    .trim()
  
  queryText.value = formatted
}

const showHistory = async () => {
  historyDialogVisible.value = true
  await fetchQueryHistory()
}

const fetchQueryHistory = async () => {
  try {
    const params: any = {
      page: historyPagination.page,
      page_size: historyPagination.pageSize
    }
    
    if (selectedConnection.value) {
      params.connection_id = selectedConnection.value
    }
    
    const response = await api.get('/database/query-history/', { params })
    
    if (response.data.success) {
      let data = response.data.data
      
      if (Array.isArray(data)) {
        queryHistory.value = data
        historyPagination.total = data.length
      } else if (data && Array.isArray(data.results)) {
        queryHistory.value = data.results
        historyPagination.total = data.total || data.results.length
      }
    }
  } catch (error) {
    console.error('获取查询历史失败:', error)
  }
}

const useHistoryQuery = (historyItem: any) => {
  queryText.value = historyItem.query
  selectedConnection.value = historyItem.connection
  historyDialogVisible.value = false
  ElMessage.success('已加载历史查询')
}

const exportResult = () => {
  if (!queryResult.value || !queryResult.value.columns) {
    ElMessage.warning('没有可导出的数据')
    return
  }

  // 构建CSV内容
  const headers = queryResult.value.columns.join(',')
  const rows = queryResult.value.rows.map((row: any[]) => 
    row.map(cell => `"${cell || ''}"`).join(',')
  ).join('\n')
  
  const csvContent = headers + '\n' + rows
  
  // 创建下载链接
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  
  link.setAttribute('href', url)
  link.setAttribute('download', `query_result_${new Date().getTime()}.csv`)
  link.style.visibility = 'hidden'
  
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('查询结果已导出')
}

// 生命周期
onMounted(() => {
  fetchConnectionList()
})
</script>

<style scoped>
.query-tool {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-actions {
  display: flex;
  gap: 8px;
}

.result-actions {
  display: flex;
  gap: 8px;
}

.query-editor {
  margin-bottom: 16px;
}

.query-textarea :deep(.el-textarea__inner) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.query-info {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #909399;
  padding: 8px 0;
  border-top: 1px solid #ebeef5;
}

.result-summary {
  margin-top: 16px;
  padding: 8px 0;
  border-top: 1px solid #ebeef5;
  font-size: 14px;
  color: #909399;
}

.execution-result,
.error-result {
  text-align: center;
  padding: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style>
